package com.marui.ch1.mypool;

import java.sql.Connection;
import java.util.LinkedList;

/**
 * @author marui
 * @date 10:04 2020/5/15
 * @since 1.0
 */
public class DBPool {
    /**
     * 连接池
     */
    private static LinkedList<Connection> pool = new LinkedList();

    public DBPool(int initalSize){
        if (initalSize >= 0){
            for (int i = 0; i < initalSize; i++) {
                pool.addLast(SqlConnectImpl.fetchConnection());
            }
        }
    }

    /**
     * 获取连接
     * @param mills
     * @return
     * @throws InterruptedException
     */
    public Connection featchConnection(long mills) throws InterruptedException {
        synchronized (pool){

        if (mills < 0) {
            while (pool.isEmpty()){
                pool.wait();
            }
            return pool.removeLast();
        } else {
            Long overtime = System.currentTimeMillis() + mills;
            Long remainTime = mills;
            while (pool.isEmpty() && remainTime > 0){
                pool.wait();
                remainTime = overtime - System.currentTimeMillis();
            }
            Connection result = null;
            if(!pool.isEmpty()){
                result = pool.removeLast();
            }
            return result;
        }

        }
    }
    /**
     * 放回数据库连接
     * @param conn
     */
    public void releaseConn(Connection conn) {
        if(conn!=null) {
            synchronized (pool) {
                pool.addLast(conn);
                pool.notifyAll();
            }
        }
    }

}
